import { Component, OnInit } from '@angular/core'
import { Router } from '@angular/router'
import { HttpClient, HttpHeaders } from '@angular/common/http'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
	isShowIcon = config.PRJ_MODEL != 2;
	validatorOptions = {
		feedbackIcons: {
			valid: 'glyphicon glyphicon-ok',
			invalid: 'glyphicon glyphicon-remove',
			validating: 'glyphicon glyphicon-refresh'
		},
		fields: {
			userName: {
				group:'.infoItem',
				validators: {
					notEmpty: {
						message: '请输入用户名称'
					}
				}
			},
			password: {
				group:'.infoItem',
				validators: {
					notEmpty: {
						message: '请输入密码'
					}
				}
			}
			// captcha: {
			// 	trigger:"input",
			// 	group:'.infoItem',
			// 	validators: {
			// 		notEmpty: {
			// 			message: '请输入验证码'
			// 		}
			// 	}
			// }
		}
	}
	userName:string = '';
	password:string = '';
	captcha:string = '';
	isLogin = false;
	imgURL = config.BaseURL+'captcha.html';
	resourceList:any[] = [];
	isRemember:any = false;
	routerUrlList:any = [];
	Year: number;
	constructor(private router: Router, private jsonApiService: JsonApiService) {}
	ngOnInit() {
	    this.Year = new Date().getFullYear();
		layer.closeAll('loading');
		common.clearCookie('isLogin');
		common.clearCookie('WEBSIDE_SID');
		common.clearCookie('hd-userName');
		common.clearCookie('hd-password');
		common.clearCookie('hd-isRemember');
		localStorage.clear();
		let userInfo = sessionStorage.getItem('hd-userInfo') ? decodeURIComponent(sessionStorage.getItem('hd-userInfo')).split('&=') : null;
		if (userInfo) {
			this.isRemember = userInfo[0];
			this.userName = userInfo[1];
			this.password = userInfo[2];
		}
		// this.initCaptcha();
	}
	// 页面跳转方法
	jumpNewPage(name){
		const url = location.origin + location.pathname + name
		window.open(url, '_blank')
	}

	// 更换验证码点击事件
	changeImg() {
		this.initCaptcha();
	}
	// 读取验证码
	initCaptcha() {
		this.imgURL = config.BaseURL + "captcha.html?" + new Date().getTime();
	}
	// 拉取菜单数据,对resourceList数据进行整合,最多支持4级菜单
	initMenu() {
		this.jsonApiService.http('index2.html',null).subscribe(
			(data) => {
				this.resourceList = [];
				this.routerUrlList = [];
				if(data.success){
					var tempArr = data.data.menu;
					if(!tempArr || tempArr.length == 0){
						this.jsonApiService.message('您没有权限访问!具体咨询管理员');
						return;
					}

        const parseMenu = (arr: any[]): any[] => {
          let map = {}
          arr.forEach(i => {
            map[i.id] = i
          })

          let treeData = []
          arr.forEach(child => {
            child.btnArr = []
            if (child.path && child.type === 0) {
              this.routerUrlList.push(child.path)
            }
            // 判断当前数据的parentId是否存在map中
            const mapItem = map[child.parentId]

            if (mapItem) {
              // 存在则表示当前数据不是最顶层数据
              if (child.type === 1) {
                ;(mapItem.btnArr || (mapItem.btnArr = [])).push(child)
              } else {
                ;(mapItem.children || (mapItem.children = [])).push(child)
              }
            } else {
              // 不存在则是顶层数据
              treeData.push(child)
            }
          })
          return treeData
        }

        const formatData = (data: any): string => {
          return encodeURIComponent(JSON.stringify(data))
        }

        this.resourceList = parseMenu(tempArr)
        localStorage.removeItem('s-menu-url')
        localStorage.setItem('s-menu-url', formatData(this.routerUrlList)) //菜单缓存到本地

					const isHome: boolean = !this.resourceList[0].children.length && this.resourceList[0].path
					const isOrdinaryMenu: boolean = this.resourceList[0].children.length && this.resourceList[0].children[0].path
					if (isHome || isOrdinaryMenu) {
						localStorage.removeItem('s-menu')
						localStorage.setItem('s-menu', formatData(this.resourceList));//菜单缓存到本地
						localStorage.setItem(
							isHome ? 'cargpsw_desktop' : `cargpsw_${this.resourceList[0].children[0].sourceKey}`,
							isHome ? formatData(this.resourceList[0].btnArr) : formatData(this.resourceList[0].children[0].btnArr)
						);
						this.router.navigate([isHome ? this.resourceList[0].path : this.resourceList[0].children[0].path]);//默认跳转第一条数据菜单,没有子菜单情况下,跳转父级
					} else {
						this.jsonApiService.message("您没有权限访问!具体咨询管理员")
					}
				}
			}
		)
	}
	login(event) {
		event.preventDefault();
		$('#loginFrom').bootstrapValidator('validate'); //开启验证
		let isValid = $('#loginFrom').data('bootstrapValidator').isValid();  //验证是否通过
		if(isValid){
			// let reqdata = 'userName='+this.userName+'&password='+this.password+'&captcha='+this.captcha;
			let reqdata = 'userName='+this.userName+'&password='+this.password;
			this.jsonApiService.http('login2.html',reqdata).subscribe(
				(data) => {
					if(data.success){
						this.isLogin = true;
						localStorage.clear()
						localStorage.setItem('token', data.data)
						//$.ajax 全局添加X-token
						$.ajaxSetup({
							headers: {
								'X-Token': localStorage.getItem('token') || ''
							}
						})
						common.setCookie('isLogin',"true",8);//登录前端设置8小时失效
						this.initMenu();//读取菜单数据
						common.setCookie("isFirst","true")
						if(this.isRemember){
							let userInfo = encodeURIComponent(this.isRemember+'&='+this.userName+'&='+this.password);
							sessionStorage.setItem('hd-userInfo',userInfo);
						}else{
							sessionStorage.removeItem('hd-userInfo');
						}
					}else{
						this.jsonApiService.message(data.message);
						common.clearCookie('isLogin');
						this.isLogin = false;
						// this.initCaptcha();
					}
				}
			)
		}
	}
}
